package my.sorter.translator.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import my.sorter.utils.DateUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String exceptionToJson(HttpServletRequest req, Exception e) throws Exception{
        Map<String,Object> errorMessage = new LinkedHashMap<>();
        StackTraceElement[] stackTraces = e.getStackTrace();
        List stacks = Collections.synchronizedList(new ArrayList<>());
        if (stacks.size()>0){
            for (StackTraceElement stackTrace:stackTraces){
                stacks.add(stackTrace.toString());
            }
        }
        errorMessage.put("exception","error");
        if (e.getMessage()!=null){
            errorMessage.put("message",e.getMessage());
        }
        errorMessage.put("time", DateUtils.nowDateToFormattedString());
        errorMessage.put("exception",stacks.toString());
        e.printStackTrace();
        return JSON.toJSONString(errorMessage);
    }
}
